<?php

namespace App\Http\Controllers\Otc;

use App\Http\Controllers\Controller;
use App\Models\Currency;
use App\Models\Enter;
use App\Models\Entrust;
use App\Models\Property;
use App\Models\Recharge;
use App\Models\RechOrder;
use App\Models\User;
use App\Traits\ValidationTrait;
use Exception;
use Illuminate\Http\Request;

class AdvertController extends Controller
{
    use ValidationTrait;

    /**
     * 商家已发布广告.
     *
     * @author hxq
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function issued_advert(Request $request)
    {
        //验证必传参数
        if (!$request->has('uid')) {
            //错误提示
            return respF(1003);
        }
        //商家用户id
        $uid = $request->get('uid');
        //验证参数是否有值
        if (empty($uid)) {
            //参数错误
            return respF(1000);
        }
        //查找用户
        $user = User::find($uid);
        //无数据
        if (!$user) {
            //用户不存在
            return respF(1001);
        }
        //条件查询订单
        $orders = RechOrder::where(['uid' => $uid])
            ->whereIn('status', [1, 2])
            ->orderBy('created_at', 'desc')
            ->paginate(10);
        //没有数据
        if (!$orders) {
            //错误提示
            return respF(1009);
        }
        //成功提示
        return response()->json(['status' => 1, 'msg' => '查询成功', 'data' => $orders]);
    }

    /**
     * 商家中心--我的订单.
     *
     * @author hxq
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function business_orders(Request $request)
    {
        $info = $request->all();
        $data = [];
        if (empty($info['uid']) || empty($info['token'])) {
            return respF(1003);
        }

        if (empty($info['genre'])) {
            $info['genre'] = 0;
        }

        $where  = GetWhereGenre($info['genre'], $info['uid'], 2);
        
        $result = Recharge::where($where)->where('status', '<>', 4)->where(function($query) use($request) {
            $order_no = $request->get('order_no');
            if ($order_no) {
                $query->where('order_no', 'like', '%'.$order_no.'%');
            }

        })->orderby('created_at', 'DESC')->paginate(10);
        
        if ($info['genre'] == 4) {
            $result = Recharge::where($where)->whereIn('status', [5, 6])->where(function($query) use($request) {
                $order_no = $request->get('order_no');
                if ($order_no) {
                    $query->where('order_no', 'like', '%'.$order_no.'%');
                }
            })->orderby('created_at', 'DESC')->paginate(10);
        }

        $data['total'] = $result->total();

        if ($result->count() <= 0) {
            return respF(1009);
        }
        $list = [];
        foreach ($result as $k => $v) {
            $list[$k]['order_no']    = $v->order_no; //订单号
            $list[$k]['nickname']    = $v->buyer->nickname; //名称
            $list[$k]['photo']       = config('alioss.host') . '/' . $v->buyer->headimg; //名称
            $list[$k]['oid']         = $v->id; //订单id
            $list[$k]['type']        = $v->type ?? null; //1为用户卖 2为用户买
            $list[$k]['total_price'] = sprintf('%.2f', $v->total_price); //总价
            $list[$k]['status']      = $v->status; //状态
            $list[$k]['num']         = $v->num; 
            $list[$k]['created_at']  = strtotime($v->created_at); //创建时间
            $list[$k]['genre']       = HandleShowStatus($v->type, $v->status, 1); //类型
        }
        $data['list'] = $list;

        //获取USDT的logo
        $usdt = Currency::where('name_en', 'USDT')->first();
        if ($usdt) {
            $data['usdt_logo'] = config('alioss.host').$usdt->logo;
        }

        //成功提示
        return response()->json(['status' => 1, 'msg' => '查询成功', 'data' => $data]);
    }

    /**
     * 撤销委托单.
     *
     * @author hxq
     *
     * @param Request $request [description]
     *
     * @return \Illuminate\Http\JsonResponse [type]           [description]
     */
    public function cancel_rech_order(Request $request)
    {
        //验证必传参数
        if (!$request->has('order_id')) {
            //错误提示
            return respF(1003);
        }
        //委托单id
        $order_id = $request->get('order_id');
        //查找订单
        $order = RechOrder::find($order_id);
        //订单不存在
        if (!$order) {
            //错误提示
            return respF(1002);
        }
        //判断是部分撤销还是全部撤销
        if ($order->total_num == $order->deal_num) {
            //全部撤销
            $order->update(['status' => 5]);
        } else {
            //部分撤销
            $order->update(['status' => 4]);
        }
        //如果是卖出，退回冻结资产
        if ($order->type == 2) {
            //USDT的币种ID
            $cid = Currency::where('name_en', 'USDT')->value('id');
            //获取用户USDT资产余额
            $property = Property::where(['uid' => $order->uid, 'cid' => $cid])->first();
            //减去冻结资产
            $property->decrement('blocked', $order->surplus_num);
            //增加可用资产
            $property->increment('balance', $order->surplus_num);
        }

        //成功提示
        return response()->json(['status' => 1, 'msg' => '撤销成功']);
    }

    /**
     * 发布广告.
     *
     * @author hxq
     *
     * @param Request $request [description]
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function create_rech_order(Request $request)
    {
        try {
            //验证
            $validator = $this->verify($request, 'validation.create_rech_order');

            if ($validator->fails()) {
                throw new Exception(1000);
            }
            //接收参数
            $input = $request->all();

            $user = User::find($input['uid']);
            //用户不存在
            if (!$user) {
                throw new Exception(1001);
            }
            //用户不是商家
            if ($user->type != 2) {
                //用户非法
                throw new Exception(2023);
            }
            $enters = $user->enters;
            if (empty($enters)){
                throw new Exception(4010);
            }
            if ($enters->status！=1){
                throw new Exception(4011);
            }
            $is_custom = 1;
            if ($input['price_section'] == '自定义') {
                $is_custom = 0;
            }
            //处理图片
            $input['qr_code'] = str_replace(config('alioss.host'), '', $input['qr_code']);
            //修改非必须传递参数
            $squeak = '';
            $qr_code = '';
            if ($input['type']==2){
                if (empty($input['squeak'])||empty($input['qr_code']))
                    throw new Exception(1000);
                $squeak = $input['squeak'];
                $qr_code = $input['qr_code'];
            }
            //写入数据库
            RechOrder::create([
                'order_no' => get_microtimes('GGD'),
                'uid' => $input['uid'],
                'type' => $input['type'],
                'site' => $input['site'],
                'price' => $input['price'],
                'total_num' => 0,
                'deal_num' => 0,
                'surplus_num' => 0,
                'trade_limit' => $input['trade_limit'],
                'trade_type' => $input['trade_type'],
                'trade_time' => $input['trade_time'],
                'status' => 1,
                'squeak' => $squeak,
                'qr_code' => $qr_code,
                'price_section' => $input['price_section'],
                'is_custom' => $is_custom,
            ]);
            //成功提示
            return response()->json(['status' => 1, 'msg' => '发布成功']);
        } catch (Exception $e) {
            //接收错误号
            $msg = $e->getMessage();

            return respF($msg);
        }
    }

    /**
     * 广告单详情.
     *
     * @author hxq
     *
     * @param Request $request [description]
     *
     * @return [type] [description]
     */
    public function rech_order_info(Request $request)
    {
        //广告单ID
        $rid = $request->get('rid');
        if (empty($rid)) {
            return respF(1000);
        }
        $data = RechOrder::find($rid)->toArray();
        $data['qr_code'] = config('alioss.host').'/'.$data['qr_code'];

        return response(['status' => 1, 'msg' => '成功', 'data' => $data]);
    }

    /**
     * 编辑广告.
     *
     * @author hxq
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function update_rech_order(Request $request)
    {
        //订单ID
        $rid = $request->get('rid');
        //所在地 1中国
        $site = $request->get('site');
        //价格
        $price = $request->get('price');
        //是否限制已交易用户购买 0不限制 1限制
        $trade_limit = $request->get('trade_limit');
        //交易时间类型 0全天 1自选
        $trade_type = $request->get('trade_type');
        //交易时间区间 例8:00-18:00
        $trade_time = $request->get('trade_time');
        //吱口令
        $squeak = $request->get('squeak');
        //二维码
        $qr_code = $request->get('qr_code');
        //修改路径-zrc 2018-5-26
        if (strpos($qr_code, '//')) {
            $img_s = parse_url($qr_code);
            $qr_code = ltrim($img_s['path'], '/');
        }
        //end 2018-5-26
        //出售数量
        $price_section = $request->get('price_section');
        //查找订单
        $order = RechOrder::find($rid);
        //订单不存在
        if (!$order) {
            //错误提示
            return respF(1002);
        }
        //修改订单
        $order->update([
            'site' => $site,
            'trade_limit' => $trade_limit,
            'trade_type' => $trade_type,
            'trade_time' => $trade_time,
            'squeak' => $squeak,
            'qr_code' => $qr_code,
            'price_section' => $price_section,
        ]);

        //成功提示
        return response()->json(['status' => 1, 'msg' => '编辑成功']);
    }
}
